import subprocess

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QGridLayout, QComboBox, QMessageBox, QLabel, QGroupBox, QLineEdit, QVBoxLayout


class NetworkInterface(QWidget):

    def set_ip(self):
        dlg = QMessageBox()
        if len(self.devices) < 2:
            msg = 'Не найдено как минимум два необходимых интерфейса. ' \
                  'Убедитесь, что рабочее устройство - панель Promethean и кабель ethernet подключён.'
        else:
            android_interface = self.android_interfaces_list.currentText()
            network_interface = self.network_interfaces_list.currentText()
            ret3 = subprocess.run(f'nmcli connection modify {self.connections[android_interface]} '
                                  f'ipv4.method manual ipv4.address {self.android_ip.text()}', shell=True).returncode
            ret1 = subprocess.run(f'nmcli connection modify {self.connections[network_interface]} '
                                  f'connection.id {self.network_name.text()}', shell=True).returncode
            ret2 = subprocess.run(f'nmcli connection modify {self.connections[android_interface]} '
                                  f'connection.id {self.android_name.text()}', shell=True).returncode
            if ret1 + ret2 + ret3 == 0:
                msg = 'Выполнено'
            else:
                msg = 'При переименовании сети или установке IP возникли ошибки.'
                if ret1:
                    msg += f'\nНевозможно переименовать {self.connections[network_interface]}'
                if ret2:
                    msg += f'\nНевозможно переименовать {self.connections[android_interface]}'
                if ret3:
                    msg += f'\nНевозможно назначить IP {self.connections[android_interface]}'
                dlg.setIcon(QMessageBox.Warning)
        dlg.setWindowTitle('Внимание')
        dlg.setText(msg)
        dlg.exec()

    def __init__(self):
        super().__init__()

        self.setWindowTitle("Выберите интерфейс")

        container_layout = QVBoxLayout()
        self.setLayout(container_layout)
        central_widget = QWidget()
        central_widget_layout = QGridLayout()
        central_widget.setLayout(central_widget_layout)
        container_layout.addWidget(central_widget)

        self.network_interfaces_list = QComboBox()
        self.android_interfaces_list = QComboBox()
        available_interfaces = subprocess.check_output('nmcli device show',
                                                       shell=True).decode().split('\n')
        self.connections = dict()
        current_device = ''
        for i in available_interfaces:
            if 'GENERAL.DEVICE:' in i:
                current_device = i.split('GENERAL.DEVICE:')[-1].strip()
            if current_device not in self.connections and 'GENERAL.CONNECTION' in i and current_device.startswith('en'):
                if i.split('GENERAL.CONNECTION:')[-1].strip() != '--':
                    self.connections[current_device] = i.split('GENERAL.CONNECTION:')[-1].strip()
                else:
                    msg = f'С интерфейсом {current_device} не связано ни одного соединения. Установить?'
                    reply = QMessageBox.question(self, 'Внимание', msg, QMessageBox.Yes, QMessageBox.No)
                    if reply == QMessageBox.Yes:
                        if 'u' in current_device:
                            ret = subprocess.run(
                                f'nmcli connection add con-name {current_device} ifname {current_device} type '
                                f'ethernet ipv4.method manual ipv4.address 192.168.254.253/24', shell=True).returncode
                        else:
                            ret = subprocess.run(f'nmcli connection add con-name {current_device} '
                                                 f'ifname {current_device} type ethernet', shell=True).returncode
                        if ret == 0:
                            self.connections[current_device] = current_device
                        else:
                            msg = QMessageBox()
                            msg.setIcon(QMessageBox.Critical)
                            msg.setInformativeText(f"Не удалось установить соединение на интерфейсе {current_device}")
                            msg.setWindowTitle("Ошибка")
                            msg.exec_()
        self.devices = list(self.connections.keys())
        self.network_interfaces_list.addItems(self.devices)
        self.android_interfaces_list.addItems(self.devices)
        network_index, android_index = 0, 0
        for i in range(len(self.devices)):
            if 'u' in self.devices[i]:
                android_index = i
                if i == 0 and len(self.devices) > 1:
                    network_index = 1
        if len(self.devices) > 1 and network_index == android_index:
            android_index = 1
        set_connection_label = QLabel('Установить соединение с Android')
        set_connection_label.setAlignment(Qt.AlignCenter)
        central_widget_layout.addWidget(set_connection_label, 0, 0, 1, 2)
        panel_type_label = QLabel('Выберите тип панели:')
        panel_type_label.setAlignment(Qt.AlignRight)
        central_widget_layout.addWidget(panel_type_label, 1, 0)
        self.panel_type_list = QComboBox()
        self.panel_type_list.addItems(['Promethean'])
        central_widget_layout.addWidget(self.panel_type_list, 1, 1)

        network_group = QGroupBox('Сеть')
        network_group_layout = QGridLayout(network_group)

        central_widget_layout.addWidget(network_group, 2, 0)

        network_group_layout.addWidget(QLabel('Интерфейс: '), 0, 0)
        network_group_layout.addWidget(self.network_interfaces_list, 0, 1)
        self.network_interfaces_list.setCurrentIndex(network_index)
        network_group_layout.addWidget(QLabel('Название: '), 1, 0)
        self.network_name = QLineEdit()
        self.network_name.setText('Сеть')
        network_group_layout.addWidget(self.network_name, 1, 1)

        android_group = QGroupBox('Android')
        android_group_layout = QGridLayout(android_group)

        central_widget_layout.addWidget(android_group, 2, 1)

        android_group_layout.addWidget(QLabel('Интерфейс: '), 0, 0)
        android_group_layout.addWidget(self.android_interfaces_list, 0, 1)
        self.android_interfaces_list.setCurrentIndex(android_index)
        android_group_layout.addWidget(QLabel('Название: '), 1, 0)
        self.android_name = QLineEdit()
        self.android_name.setText('Android')
        android_group_layout.addWidget(self.android_name, 1, 1)
        android_group_layout.addWidget(QLabel('IP: '), 2, 0)
        self.android_ip = QLineEdit()
        self.android_ip.setText('192.168.254.253/24')
        android_group_layout.addWidget(self.android_ip, 2, 1)

        central_widget_layout.setRowStretch(0, 0)
        central_widget_layout.setRowStretch(1, 0)
        central_widget_layout.setRowStretch(2, 1)

        container_layout.addStretch()
